package fragmentson;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import activity.SonActivity;
import bean.MessageForSimple;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import util.dialog.DialogForPhoto;


/**
 * 设备详情
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class AddCar_B extends BackHandledFragment {

	private View rootView;
	private ImageView iv_add_photo1,iv_add_photo2,iv_add_photo3,iv_add_photo4,iv_add_photo5,iv_add_photo6,iv_add_photo7,iv_add_photo8,iv_add_photo9;
	private ImageView iv_delete_photo1,iv_delete_photo2,iv_delete_photo3,iv_delete_photo4,iv_delete_photo5,iv_delete_photo6,iv_delete_photo7,iv_delete_photo8,iv_delete_photo9;
	//照片
	private int SYS_INTENT_REQUEST = 0XFF01,CAMERA_INTENT_REQUEST = 0XFF02,IMAGE_CUT = 1;
	public String photoPath,filename="";
	private Uri photoUri,imageUri;
	private int nowPhotoIndex = 0;
	private String deviceid="";
	private HashMap<String,String> map = new HashMap<>();
	private Bitmap bmp;
	private String attribute1,attribute2,attribute3,attribute4,attribute5,attribute6,attribute7,attribute8,attribute9,sign;
	private View ll_linear5,ll_linear6,ll_linear7;
	private TextView tv_textview5,tv_textview6,tv_textview7;
	private String propertyid="",policeid="",producerid="";

    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_addcar_b, null);
		attribute1 = getArguments().getString("attribute1");
		attribute2 = getArguments().getString("attribute2");
		attribute3 = getArguments().getString("attribute3");
		attribute4 = getArguments().getString("attribute4");
		attribute5 = getArguments().getString("attribute5");
		attribute6 = getArguments().getString("attribute6");
		attribute7 = getArguments().getString("attribute7");
		attribute8 = getArguments().getString("attribute8");
		attribute9 = getArguments().getString("attribute9");
		initView();
		initMap();
		return rootView;
	}

	private void initMap(){
		for(int i=1;i<10;i++) {
			map.put(i+"", "");
		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) rootView.findViewById(R.id.tv_title)).setText(R.string.add_car);
         rootView.findViewById(R.id.tv_next).setOnClickListener(listener);
		iv_add_photo1 = (ImageView)rootView.findViewById(R.id.iv_add_photo1);
		iv_add_photo2 = (ImageView)rootView.findViewById(R.id.iv_add_photo2);
		iv_add_photo3 = (ImageView)rootView.findViewById(R.id.iv_add_photo3);
		iv_add_photo4 = (ImageView)rootView.findViewById(R.id.iv_add_photo4);
		iv_add_photo5 = (ImageView)rootView.findViewById(R.id.iv_add_photo5);
		iv_add_photo6 = (ImageView)rootView.findViewById(R.id.iv_add_photo6);
		iv_add_photo7 = (ImageView)rootView.findViewById(R.id.iv_add_photo7);
		iv_add_photo8 = (ImageView)rootView.findViewById(R.id.iv_add_photo8);
		iv_add_photo9 = (ImageView)rootView.findViewById(R.id.iv_add_photo9);
		iv_delete_photo1 = (ImageView)rootView.findViewById(R.id.iv_delete_photo1);
		iv_delete_photo2 = (ImageView)rootView.findViewById(R.id.iv_delete_photo2);
		iv_delete_photo3 = (ImageView)rootView.findViewById(R.id.iv_delete_photo3);
		iv_delete_photo4 = (ImageView)rootView.findViewById(R.id.iv_delete_photo4);
		iv_delete_photo5 = (ImageView)rootView.findViewById(R.id.iv_delete_photo5);
		iv_delete_photo6 = (ImageView)rootView.findViewById(R.id.iv_delete_photo6);
		iv_delete_photo7 = (ImageView)rootView.findViewById(R.id.iv_delete_photo7);
		iv_delete_photo8 = (ImageView)rootView.findViewById(R.id.iv_delete_photo8);
		iv_delete_photo9 = (ImageView)rootView.findViewById(R.id.iv_delete_photo9);
		iv_add_photo1.setOnClickListener(listener);
		iv_add_photo2.setOnClickListener(listener);
		iv_add_photo3.setOnClickListener(listener);
		iv_add_photo4.setOnClickListener(listener);
		iv_add_photo5.setOnClickListener(listener);
		iv_add_photo6.setOnClickListener(listener);
		iv_add_photo7.setOnClickListener(listener);
		iv_add_photo8.setOnClickListener(listener);
		iv_add_photo9.setOnClickListener(listener);

		iv_delete_photo1.setOnClickListener(listener);
		iv_delete_photo2.setOnClickListener(listener);
		iv_delete_photo3.setOnClickListener(listener);
		iv_delete_photo4.setOnClickListener(listener);
		iv_delete_photo5.setOnClickListener(listener);
		iv_delete_photo6.setOnClickListener(listener);
		iv_delete_photo7.setOnClickListener(listener);
		iv_delete_photo8.setOnClickListener(listener);
		iv_delete_photo9.setOnClickListener(listener);

		ll_linear5 = rootView.findViewById(R.id.ll_linear5);
		ll_linear6 = rootView.findViewById(R.id.ll_linear6);
		ll_linear7 = rootView.findViewById(R.id.ll_linear7);
		ll_linear5.setOnClickListener(listener);
		ll_linear6.setOnClickListener(listener);
		ll_linear7.setOnClickListener(listener);
		tv_textview5 = ((TextView) rootView.findViewById(R.id.tv_textview5));
		tv_textview6 = ((TextView) rootView.findViewById(R.id.tv_textview6));
		tv_textview7 = ((TextView) rootView.findViewById(R.id.tv_textview7));

	}

	public static AddCar_B newInstance(String attribute1,String attribute2,String attribute3,String attribute4,String attribute5,String attribute6,String attribute7,String attribute8,String attribute9) {
		AddCar_B fragment = new AddCar_B();
		Bundle bundle = new Bundle();
		bundle.putString("attribute1",attribute1);
		bundle.putString("attribute2",attribute2);
		bundle.putString("attribute3",attribute3);
		bundle.putString("attribute4",attribute4);
		bundle.putString("attribute5",attribute5);
		bundle.putString("attribute6",attribute6);
		bundle.putString("attribute7",attribute7);
		bundle.putString("attribute8",attribute8);
		bundle.putString("attribute9",attribute9);
		fragment.setArguments(bundle);
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				case R.id.iv_add_photo1:
					nowPhotoIndex = 1;
					showDialog();
					break;
				case R.id.iv_add_photo2:
					nowPhotoIndex = 2;
					showDialog();
					break;
				case R.id.iv_add_photo3:
					nowPhotoIndex = 3;
					showDialog();
					break;
				case R.id.iv_add_photo4:
					nowPhotoIndex = 4;
					showDialog();
					break;
				case R.id.iv_add_photo5:
					nowPhotoIndex = 5;
					showDialog();
					break;
				case R.id.iv_add_photo6:
					nowPhotoIndex = 6;
					showDialog();
					break;
				case R.id.iv_add_photo7:
					nowPhotoIndex = 7;
					showDialog();
					break;
				case R.id.iv_add_photo8:
					nowPhotoIndex = 8;
					showDialog();
					break;
				case R.id.iv_add_photo9:
					nowPhotoIndex = 9;
					showDialog();
					break;
				case R.id.iv_delete_photo1:
					map.put("1","");
					iv_add_photo1.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo2:
					map.put("2","");
					iv_add_photo2.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo3:
					map.put("3","");
					iv_add_photo3.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo4:
					map.put("4","");
					iv_add_photo4.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo5:
					map.put("5","");
					iv_add_photo5.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo6:
					map.put("6","");
					iv_add_photo6.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo7:
					map.put("7","");
					iv_add_photo7.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo8:
					map.put("8","");
					iv_add_photo8.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.iv_delete_photo9:
					map.put("9","");
					iv_add_photo9.setImageResource(R.mipmap.icon_add_photo);
					v.setVisibility(View.GONE);
					break;
				case R.id.tv_next:
					sign = "";
					for(int i=1;i<10;i++){
						if(i!=9) {
							sign = sign + map.get(i + "") + ",";
						}else{
							sign = sign + map.get(i + "");
						}
					}
					add();
					break;
				case R.id.ll_linear5:
					((SonActivity) getActivity()).addFragment(DeviceProperty.newInstance(new DeviceProperty.CallBackListener() {
						@Override
						public void listener(String item,String id) {
							propertyid = id;
							tv_textview5.setText(item);
						}
					},"5",""),true);
					break;
				case R.id.ll_linear6:
					((SonActivity) getActivity()).addFragment(DeviceProperty.newInstance(new DeviceProperty.CallBackListener() {
						@Override
						public void listener(String item,String id) {
							policeid = id;
							tv_textview6.setText(item);
						}
					},"6",""),true);
					break;
				case R.id.ll_linear7:
					((SonActivity) getActivity()).addFragment(DeviceProperty.newInstance(new DeviceProperty.CallBackListener() {
						@Override
						public void listener(String item,String id) {
							producerid = id;
							tv_textview7.setText(item);
						}
					},"7",""),true);
					break;
				default:
					break;
			}
		}
	};

	/**
	 * 打开系统相册
	 */
	private void systemPhoto() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, SYS_INTENT_REQUEST);
	}

	/**
	 * 调用相机拍照
	 */
	private void cameraPhoto() {
		String sdStatus = Environment.getExternalStorageState();
		/* 检测sd是否可用 */
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			Toast.makeText(getActivity(),"SD卡不可用",Toast.LENGTH_LONG).show();
			return;
		}
		//图片名称 时间命名
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date(System.currentTimeMillis());
		filename = format.format(date);
		//创建File对象用于存储拍照的图片 SD卡根目录
		//File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);
		//存储至DCIM文件夹
		File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		File outputImage = new File(path,filename+".jpg");
		try {
			if(outputImage.exists()) {
				outputImage.delete();
			}
			outputImage.createNewFile();
		} catch(IOException e) {
			e.printStackTrace();
		}
		//将File对象转换为Uri并启动照相程序
		imageUri = Uri.fromFile(outputImage);
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); //照相
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //指定图片输出地址
		//拍完照startActivityForResult() 结果返回onActivityResult()函数
		startActivityForResult(intent, CAMERA_INTENT_REQUEST);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == SYS_INTENT_REQUEST
				&& resultCode == getActivity().RESULT_OK&&data !=null) {
			cameraCamera(data);
		} else if (requestCode == CAMERA_INTENT_REQUEST
				&& resultCode == getActivity().RESULT_OK) {
			cameraCamera();
		} else if (requestCode == IMAGE_CUT
				&& resultCode == getActivity().RESULT_OK) {
			bmp = data.getParcelableExtra("data");
			if(bmp==null){
				if(photoUri!=null){
					try {
						bmp = BitmapFactory.decodeStream(
								getActivity().getContentResolver().openInputStream(photoUri));
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			photoPath = photoUri.getEncodedPath();
			ApiUtil.getApiService().saveImg(DemoApplication.getToken(), ApiUtil.upload(photoPath)).enqueue(new Callback<MessageForSimple>() {
				@Override
				public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
					try {
						MessageForSimple entity = response.body();
						if(entity.getCode().equals("10008")){
							map.put(nowPhotoIndex+"",entity.getData().getPicurl());
							setPhoto(bmp);
						}else{
							Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				@Override
				public void onFailure(Call<MessageForSimple> call, Throwable t) {
					Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
				}
			});
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 拍照后获取照片
	 */
	private void cameraCamera() {
		Uri uri = null;
		if(imageUri!=null){
			uri = imageUri;
		}
		Intent intent = getImageClipIntent(uri);
		//广播刷新相册
		Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		intentBc.setData(imageUri);
		getActivity().sendBroadcast(intentBc);
		startActivityForResult(intent, IMAGE_CUT);
	}

	/**
	 * @param data
	 * 相册选择后后获取照片
	 */
	private void cameraCamera(Intent data) {
		Uri uri = data.getData();
		// 相册中文件绝对路径
		Intent intent = getImageClipIntent(uri);
		startActivityForResult(intent, IMAGE_CUT);
	}

	/**
	 * 获取剪切后的图片
	 */
	public Intent getImageClipIntent(Uri uri) {
		//图片名称 时间命名
		File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		File outputImage = new File(path,"1.jpg");
		try {
			if(outputImage.exists()) {
				outputImage.delete();
			}
			outputImage.createNewFile();
		} catch(IOException e) {
			e.printStackTrace();
		}
		//将File对象转换为Uri并启动照相程序
		photoUri = Uri.fromFile(outputImage);

		Intent intent = new Intent("com.android.camera.action.CROP", null);
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("scale", true);
		intent.putExtra("crop", true);
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);// 输出图片大小
		intent.putExtra("outputY", 200);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("return-data", false);
		return intent;
	}

	private void setPhoto(Bitmap bmp){
		switch (nowPhotoIndex){
			case 1:
				iv_add_photo1.setImageBitmap(bmp);
				iv_delete_photo1.setVisibility(View.VISIBLE);
				break;
			case 2:
				iv_add_photo2.setImageBitmap(bmp);
				iv_delete_photo2.setVisibility(View.VISIBLE);
				break;
			case 3:
				iv_add_photo3.setImageBitmap(bmp);
				iv_delete_photo3.setVisibility(View.VISIBLE);
				break;
			case 4:
				iv_add_photo4.setImageBitmap(bmp);
				iv_delete_photo4.setVisibility(View.VISIBLE);
				break;
			case 5:
				iv_add_photo5.setImageBitmap(bmp);
				iv_delete_photo5.setVisibility(View.VISIBLE);
				break;
			case 6:
				iv_add_photo6.setImageBitmap(bmp);
				iv_delete_photo6.setVisibility(View.VISIBLE);
				break;
			case 7:
				iv_add_photo7.setImageBitmap(bmp);
				iv_delete_photo7.setVisibility(View.VISIBLE);
				break;
			case 8:
				iv_add_photo8.setImageBitmap(bmp);
				iv_delete_photo8.setVisibility(View.VISIBLE);
				break;
			case 9:
				iv_add_photo9.setImageBitmap(bmp);
				iv_delete_photo9.setVisibility(View.VISIBLE);
				break;
		}
	}

	private void showDialog(){
		DialogForPhoto dialog = new DialogForPhoto(getActivity());
		dialog.setSureListener(new DialogForPhoto.Sure() {
			@Override
			public void onSure(int item) {
				switch (item){
					case 1:
						cameraPhoto();
						break;
					case 2:
						systemPhoto();
						break;
					default:
						break;
				}
			}
		});
		dialog.show();
	}
	private void add(){
		ApiUtil.getApiService().devicePut(DemoApplication.getToken(),attribute1,attribute2,attribute3,attribute4,attribute5,attribute6,attribute7,attribute8,attribute9,sign,propertyid,policeid,producerid).enqueue(new Callback<MessageForSimple>() {
			@Override
			public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
				try {
					MessageForSimple entity = response.body();
					if(entity.getCode().equals("10008")){
						deviceid = entity.getData().getDeviceid();
						((SonActivity) getActivity()).backTask();
						((SonActivity) getActivity()).backTask();
						((SonActivity) getActivity()).addFragment(AddDevice.newInstance(deviceid));
					}else{
						Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Call<MessageForSimple> call, Throwable t) {
				Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
			}
		});
	}

	@Override
	public boolean onBackPressed() {
		return false;
	}
	
}
